<?php

namespace plugin\muadmin\app\admin\controller;

use plugin\muadmin\app\common\base\BaseAdminController;
use plugin\muadmin\app\common\model\Admin;
use plugin\muadmin\app\common\model\AuthRule;
use plugin\muadmin\app\common\model\SysConfig;

class Index extends BaseAdminController
{
    protected $noNeedLogin = ['login'];
//    protected $noHasModel  = ['index'];
    public function index()
    {
        $userInfo = $this->auth->getUserInfo();
        if(empty($userInfo)){
            return redirect('/app/muadmin/admin/index/login');
        }
        $temUserInfo = AuthRule::where('name','general/profile')->find();
        $this->assignConfig('adminInfo',$this->auth->getUserInfo());
        $this->assignConfig('temUserInfo',$temUserInfo);
        return $this->fetch();
    }
    public function login()
    {
        if($this->request->isAjax()){
            $data = $this->request->input('row');
            $res = $this->auth->login($data['username'],$data['password']);
            if(!$res){
                return $this->error($this->auth->getError());
            }
            return $this->success('登录成功',$data,'/app/muadmin/admin/index/index');
        }
//        return json(['code'=>1,'msg'=>'请登录']);
        return $this->fetch();
    }

    /**
     * 获取菜单
     * @return \support\Response
     */
    public function menu()
    {
        $res = $this->auth->getAdminMenu();
        $min = min(array_column($res,'pid')??[0]);
        $res = list_to_tree($res,'id','pid','children',$min);
        return $this->success('获取成功',$res);
    }
    public function logout()
    {
        $this->auth->logout();
        return $this->success('退出成功');
    }
    public function get_user_info()
    {
        $userInfo = Admin::where('id',$this->auth->id)->withoutField('password,salt,username')->find();
        return $this->success('ok',$userInfo);
    }

    /**
     * 修改主题颜色
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function change_theme_color()
    {
        $theme_color = $this->param('theme_color');
        if(empty($theme_color)){
            return $this->error('请选择主题颜色');
        }
        $has = SysConfig::where('name','theme_color')
            ->find();
        if(empty($has)){
            SysConfig::create([
                'name'=>'theme_color',
                'value'=>$theme_color,
                'group'=>'basic',
                'title'=>'主题颜色',
                'type'=>'color'
            ]);
        }else{
            $has->value = $theme_color;
            $has->save();
        }
        return $this->success('修改成功');
    }
}